#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<wait.h>
int main(){
	int fd;
	pid_t pid;
	struct flock rdlock , wrlock;
	//读锁
	rdlock.l_type = F_RDLCK;
	rdlock.l_start = 0;
	rdlock.l_whence = SEEK_SET;
	rdlock.l_len = 0;
	//写锁
	wrlock.l_type = F_WRLCK;
	wrlock.l_start = 0;
	wrlock.l_whence = SEEK_SET;
	wrlock.l_len = 0;
	
	if(fd = open("demo.txt",O_RDWR) <0){
		printf("无法打开\n");
		exit(EXIT_FAILURE);
	}
	if(write(fd,"sujingxin",9)!=9){
		printf("无法写入\n");
		exit(EXIT_FAILURE);
	}
	pid = fork();//创建子进程
	if(pid < 0 ){
		//EXIT_FAILURE
		printf("cannot fock\n");
		exit(EXIT_FAILURE);
	}
	if(pid == 0){
		//对于子进程
		printf("子进程跑起来了\n");
		if(fcntl(fd,F_GETLK,&rdlock) == -1){
			printf("子进程无法加锁\n");
			exit(EXIT_FAILURE);
		}
		if(rdlock.l_type == F_UNLCK){
			//如果文件未加锁，则上锁，否则解锁
			printf("读锁off\n");
		}else{
			char * tmp;
			read(fd,tmp,4);
			printf("读锁on\n");
			printf("读取的值为:%s\n",tmp);
		}
	}else{
		//对于父进程
		printf("父进程跑起来了\n");
		if(fcntl(fd,F_SETLK,&wrlock) == -1){
			printf("父进程无法加锁\n");
			exit(EXIT_FAILURE);
		}else if(write(fd,"aaaa",4)!=4){
			printf("无法写入\n");
			exit(EXIT_FAILURE);
		}
		wait(NULL);
	}
	close(fd);
	return 0;
}